//
//  WmcEditWatermarkVC.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/10.
//

import UIKit
import YPBedrock

public extension WmcButtonItemType {
    /// 水印编辑导航条
    enum EditWMNavigation {
        /// 分享水印
        case shareWatermark

        /// 自定义
        case custom(view: UIView)
    }

    /// 水印编辑基础属性
    enum EditWMBasicItem {
        /// 水印透明度
        case alpha

        /// 水印大小
        case size
    }
}

// MARK: - WmcEditWatermarkVC + WmcNavigatorProtocol

extension WmcEditWatermarkVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.editWatermark]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        var vm = WmcEditWatermarkVM()
        if let viewModel = parms.context as? WmcEditWatermarkVM {
            vm = viewModel
        }
        let vc = WmcEditWatermarkVC(vm)
        vc.title = vm.watermarkTitle
        return vc
    }
}

// MARK: - WmcEditWatermarkVC + WmcVMProtocol

extension WmcEditWatermarkVC: WmcVMProtocol {
    typealias VMType = WmcEditWatermarkVM
}

// MARK: - [WmcEditWatermarkVC]

class WmcEditWatermarkVC: WmcBaseVC {
    // Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        viewModel.loadData()

        // 驱动
        // 刷新
        YPWmcDrivingManager.shared.watermarkEdit_reloadTableDataBlock = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.tableView.reloadData()
        }
        // 修改条目
        YPWmcDrivingManager.shared.watermarkEdit_changeWatermarkOptionBlock = { [weak self] index, option in
            guard let weakSelf = self else { return }
            weakSelf.changeWatermarkOption(index, option: option)
        }
        // 更新水印模型
        YPWmcDrivingManager.shared.watermarkEdit_reloadWatermarkModelBlock = { [weak self] wmModel in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.updateWatermarkModel(wmModel)
        }
    }

    // Internal

    lazy var watermarkPreview: WmcEditWatermarkPreview = {
        let view = WmcEditWatermarkPreview()
        return view
    }()

    lazy var tableView: UITableView = {
        var registers: [YPRegister] = [
            YPRegister(WmcEditWatermarkAttributeCell.self),
            YPRegister(WmcEditWatermarkBrandCell.self),
            YPRegister(WmcEditWatermarkSettingCell.self),
        ]
        if let _registers = editWatermarkDelegate?.tableViewRegisterCell(.current) {
            registers.append(contentsOf: _registers)
        }
        let tableView = UITableView.YP.Create(style: .plain,
                                              delegate: self,
                                              dataSource: self,
                                              registers: registers)
        tableView.contentInset = .init(top: 0, left: 0, bottom: 74 + Wmc_safeAreaBottom, right: 0)
        return tableView
    }()

    lazy var completeBtn: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = .wmc_mainTheme
        btn.layer.cornerRadius = 4
        btn.layer.masksToBounds = true
        btn.setTitle("完成", for: .normal)
        btn.titleLabel?.font = 14.wmc_font
        return btn
    }()

    lazy var editFieldContentView: WmcEditFieldContentView = {
        let view = WmcEditFieldContentView()
        return view
    }()

    lazy var starkView: UIStackView = {
        let view = UIStackView()
        view.alignment = .fill
        view.distribution = .fill
        view.axis = .horizontal
        view.spacing = 8
        return view
    }()

    lazy var shareWatermarkBtn: WmcLeftImgRightTextBtn = {
        let btn = WmcLeftImgRightTextBtn(title: "微信分享", image: "wechat_icon_color".wmc_image)
        btn.font = 14.wmc_font
        btn.textColor = .wmc_grayH2_323233
        btn.imgSize = 24
        btn.imgTextSpacing = 5
        btn.label.textAlignment = .right
        btn.yp.layoutWidthEqual(90)
        return btn
    }()

    var dataList: [[Any]] = []

    /// 水印编辑页的外部代理
    var editWatermarkDelegate: WmcEditWatermarkDelegate? {
        return YPWmcManager.shared.uiDelegate.editWatermarkDelegate
    }

    override func backAction() {
        viewModel.editComplete() // 调用完成
        super.backAction()
    }

    override func makeUI() {
        makeNavView()

        navView.addSubview(starkView)
        starkView.snp.makeConstraints { make in
            make.centerY.equalTo(navView.backImageView)
            make.height.equalTo(24)
            make.right.equalTo(-Wmc_standardEdge.right)
        }

        addSubview(watermarkPreview)
        watermarkPreview.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(230.wmc_autoVer)
        }

        addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(watermarkPreview.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }

        addSubview(completeBtn)
        completeBtn.snp.makeConstraints { make in
            make.left.equalTo(Wmc_standardEdge.left)
            make.right.equalTo(-Wmc_standardEdge.right)
            make.height.equalTo(44)
            make.bottom.equalTo(-6 - Wmc_safeAreaBottom)
        }

        reloadNavigationItem()
    }

    override func bindViewAction() {
        // 点击分享水印
        shareWatermarkBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self,
                  let wmModel = weakSelf.viewModel.editWatermarkModelRelay.value else { return }
            let vm = WmcShareWatermarkVM()
            vm.watermarkModel = wmModel
            WmcNavigatorManager.push(.shareWatermark, parms: vm)
        }

        // 点击完成
        completeBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.backAction() // 调用返回（自带保存）
        }

        // 编辑条目完成
        editFieldContentView.submitBlock = { [weak self] idx, model in
            guard let weakSelf = self else { return }
            // 数据源修改
            weakSelf.changeWatermarkOption(idx.row, option: model)
        }
    }

    override func bindViewModel() {
        // 返回后台
        WmcAppStateManager.shared.appEnterBackground.subscribe(onNext: { [weak self] value in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.editComplete() // 调用完成
        }).disposed(by: rx.disposeBag)

        // 绑定列表数据
        viewModel.editListRelay.skip(1).subscribe(onNext: { [weak self] list in
            guard let weakSelf = self,
                  let watermarkModel = weakSelf.viewModel.watermarkModel else { return }
            // 属性列表
            let attList = weakSelf.reloadAttributeList(attList: list,
                                                       watermarkModel: watermarkModel)
            // 基础属性配置
            let basicList = weakSelf.reloadBasicList(watermarkModel: watermarkModel)
            weakSelf.dataList = [
                attList, basicList,
            ]
            weakSelf.tableView.reloadData()
            }).disposed(by: rx.disposeBag)

        // 水印预览数据同步
        viewModel.editWatermarkModelRelay.subscribe(onNext: { [weak self] model in
            guard let weakSelf = self,
                  let model = model else { return }
            let styleMode = weakSelf.viewModel.watermarkStyleMode
            weakSelf.watermarkPreview.setWatermarkModel(model,
                                                        styleMode: styleMode)
            // 通知外部水印模型重新载入
            YPWmcManager.shared.uiDelegate.editWatermarkDelegate?.watermarkModelReload(attribute: .current,
                                                                                       watermarkModel: model)
            }).disposed(by: rx.disposeBag)
    }
}
